package com.panvan.android;

import androidx.activity.result.ActivityResultLauncher;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.DownloadListener;
import android.webkit.WebView;
import android.widget.Toast;

import com.panvan.android.R;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    WebView mainView;
    WebViewInit webViewInit;
    WebViewInputCamera webViewInputCamera;

    Vibrator vibrator;

    public ActivityResultLauncher<Intent> cameraLauncher;
    public ActivityResultLauncher<Intent> checkFileLauncher;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        initWakeLook();


        //初始化webView
        this.webViewInit= initWebView();
        this.webViewInputCamera=new WebViewInputCamera(this,this.mainView);
        this.cameraLauncher= this.webViewInputCamera.createCameraLauncher();
        this.checkFileLauncher= this.webViewInputCamera.createCheckFileLauncher();

        this.vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE) ;
        //打开欢迎窗口，为webView加载资源提供过度
        openWelcome();
    }


    PowerManager pm;
    PowerManager.WakeLock mWakelock;

    public long WAKE_ACQUIRE_TIME=3000L;

    @SuppressLint("InvalidWakeLockTag")
    public void initWakeLook() {
        pm = (PowerManager) getSystemService(POWER_SERVICE);
        mWakelock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP |
                PowerManager.SCREEN_DIM_WAKE_LOCK |
                PowerManager.ON_AFTER_RELEASE, "target");

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.harry.action.wake");
        intentFilter.addAction("com.harry.action.sleep");
        registerReceiver(new MyReceiver(), intentFilter);
    }

    /**
     * 亮屏
     */
    public void wakeLockOpen(){
        Intent wakeIntent = new Intent();
        wakeIntent.setAction("com.harry.action.wake");
        sendBroadcast(wakeIntent);
    }
    /**
     * 亮屏
     */
    public void wakeLockOpen(long wakeTime){
        WAKE_ACQUIRE_TIME=wakeTime;
        wakeLockOpen();
    }
    /**
     * 熄屏
     */
    public void wakeLockClose(){
        Intent sleepIntent = new Intent();
        sleepIntent.setAction("com.harry.action.sleep");
        sendBroadcast(sleepIntent);
    }


    //记录用户首次点击返回键的时间
    private long firstTime = 0;
    @Override
    //设置回退
    //覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if((keyCode == KeyEvent.KEYCODE_BACK) && mainView.canGoBack()) {
            mainView.goBack();//goBack()表示返回WebView的上一页面
            return true;
        }
        if(!mainView.canGoBack()) {
            onBackPressed();
        }

        return false;
//        new AlertDialog.Builder(this)
//                .setMessage("是否要退出当前应用?").setPositiveButton("是", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
////                        System.exit(0);
//                        finish();
//                    }
//                })
//                .setNegativeButton("否", null)
//                .show();
//        return false;
    }

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - firstTime) > 2000) {
            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
            firstTime = System.currentTimeMillis();
        } else {
            System.exit(0);
            finish();
        }
    }


    /**
     * 打开欢迎界面
     */
    public void openWelcome() {
        Intent intent = new Intent();
        intent.setClass(this, WelComeActivity.class);
        startActivity(intent);
    }

    /**
     * 初始化webView
     */
    public WebViewInit initWebView(){
        mainView = MainActivity.this.findViewById(R.id.mainWeb);
        WebViewInit webViewInit=new WebViewInit(MainActivity.this,this.mainView,this);
//        webViewInit.initWebView();
//        setWebViewDownLoad();
        WebViewDownloadListener webViewDownloadListener=new WebViewDownloadListener(this);
        mainView.setDownloadListener(webViewDownloadListener);
        return webViewInit;

    }

    /**
     * 設置下載
     */
    private void setWebViewDownLoad(){
        mainView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                startActivity(intent);
            }
        });
    }
    
    class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if ("com.harry.action.wake".equals(intent.getAction())) {
                mWakelock.acquire(WAKE_ACQUIRE_TIME);
            }

            if ("com.harry.action.sleep".equals(intent.getAction())) {
                mWakelock.release();
            }
        }
    }
}
